import { PlusOutlined, ArrowUpOutlined, ArrowDownOutlined } from '@ant-design/icons';
import { Button, message, Upload, Input, Drawer } from 'antd';
import React, { useState, useRef } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProForm, { ModalForm, DrawerForm, ProFormText, ProFormSelect, ProFormTextArea } from '@ant-design/pro-form';
import ProDescriptions from '@ant-design/pro-descriptions';
import CSV from '../../components/csv';
import api from '@/services/ant-design-pro/api';
import FileSaver from 'file-saver'
import { reject, toInteger } from 'lodash';
import {generateForm, castType} from '../generateForm'
import CourseTime from '../CourseTime';
import csvSaver from '@/components/csvSaver';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');
  console.log(fields)
  try {
    await api.addcourse(fields);
    hide();
    message.success('Added successfully');
    return true;
  } catch (error) {
    hide();
    message.error('Adding failed, please try again!');
    return false;
  }
};
/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */

const handleUpdate = async (id, fields) => {
  const hide = message.loading('Configuring');

  try {
    await api.updatecourse({'id': id, ...fields});
    hide();
    message.success('Configuration is successful');
    return true;
  } catch (error) {
    hide();
    console.log(error)
    message.error('Configuration failed, please try again!');
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await api.removecourse(selectedRows.map((row) => row.id));
    hide();
    message.success('Deleted successfully and will refresh soon');
    return true;
  } catch (error) {
    hide();
    message.error('Delete failed, please try again');
    return false;
  }
};

const courseList = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, handleModalVisible] = useState(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */

  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [showDetail, setShowDetail] = useState(false);
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const intl = useIntl();
  const refreshTable = () => actionRef.current?.reloadAndRest?.();
  const columns = [
    {
      title: 
      (
        <FormattedMessage
          id="pages.course.name"
        />
      ),
      dataIndex: 'name',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: 
      <FormattedMessage id="pages.course.teacher" defaultMessage="teacher" />,
      dataIndex: 'teacher',
      //valueType: 'textarea',
    },
    {
      title: 
      <FormattedMessage id="pages.course.grade" defaultMessage="grade" />,
      dataIndex: 'grade',
      //valueType: 'textarea',
    },
    // {
    //   title: 
    //   <FormattedMessage id="pages.course.current" defaultMessage="current" />,
    //   dataIndex: 'select_cnt',
    //   //valueType: 'textarea',
    // },
    {
      title: 
      <FormattedMessage id="pages.course.total" defaultMessage="total" />,
      dataIndex: 'total',
      //valueType: 'textarea',
    },
    {
      title: 
      <FormattedMessage id="pages.course.time" defaultMessage="time" />,
      dataIndex: 'time',
      //hideInForm: true,
      valueEnum: CourseTime,
      castType: "int", // for format convert when load from csv
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            //handleUpdateModalVisible(true);
            setCurrentRow(record);
            setShowDetail(true)
          }}
        >
          <FormattedMessage id="pages.item.edit" defaultMessage="Edit" />
        </a>,
        <a key="delete"
          onClick={async () => {
              await handleRemove([record]);
              actionRef.current?.reloadAndRest?.();
          }}>
          <FormattedMessage
            id="pages.item.remove"
            defaultMessage="Remove"
          />
        </a>,
      ],
      ignore: (true)
    },
  ];

  const saver = new csvSaver(columns)

  const uploadProps = {
    accept: ".csv",
    customRequest: async function(option) {
      console.log(option)
      const columns = await saver.loadFromFile(option.file)
      console.log(columns)
      if (!columns || !saver.checkColums(columns)) {
        console.log('err')
        const err = intl.formatMessage({
          id: 'pages.items.CSVParseError',
          defaultMessage: 'csv parse fail',
        })
        message.error(err)
        option.onError(new Error(err))
        return
      }
      const succ = intl.formatMessage({
        id: 'pages.items.CSVParseSucc',
        defaultMessage: 'csv parse succ',
      })
      if (!await handleAdd(columns)) {
        option.onError(new Error("add fail"))
        return
      }
      option.onSuccess()
      message.success(succ)
      refreshTable()
    }
  }

  return (
    <PageContainer>
      <ProTable
        headerTitle={intl.formatMessage({
          id: 'menu.list.course-list',
          defaultMessage: 'Enquiry form',
        })}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            //type="primary"
            key="exportEmpty"
            onClick={() => {
              saver.exportToFileEmpty()
            }}
          >
            <ArrowDownOutlined /> <FormattedMessage id="pages.items.exportEmpty" defaultMessage="export empty" />
          </Button>,
          <Button
            //type="primary"
            key="new"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
          <Upload {...uploadProps}>
            <Button
              type="primary"
              key="importBatch"
            >
            <ArrowUpOutlined /> <FormattedMessage id="pages.items.importBatch" defaultMessage="import batch" />
          </Button>,
        </Upload>
        ]}
        request={api.course}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
        pagination={{pageSizeOptions: [10, 20, 50, 100, 500, 1000]}}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
              &nbsp;&nbsp;
              {/* <span>
                <FormattedMessage
                  id="pages.searchTable.totalServiceCalls"
                  defaultMessage="Total number of service calls"
                />{' '}
                {selectedRowsState.reduce((pre, item) => pre + item.callNo, 0)}{' '}
                <FormattedMessage id="pages.searchTable.tenThousand" defaultMessage="万" />
              </span> */}
            </div>
          }
        >
          <Button type="primary"
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>

          <Button type="primary"
            onClick={() => {
              saver.exportToFile(selectedRowsState)
              setSelectedRows([])
              //actionRef.current?.reloadAndRest?.();
            }}
          >
            <FormattedMessage
              id="pages.items.exportBatch"
              defaultMessage="Batch output to csv"
            />
          </Button>

          {/* <Button type="primary">
            <FormattedMessage
              id="pages.searchTable.batchApproval"
              defaultMessage="Batch approval"
            />
          </Button> */}
        </FooterToolbar>
      )}
      <ModalForm
        title=
        {intl.formatMessage({
          id: 'pages.courseTable.Add',
          defaultMessage: 'Add course',
        })}
        width="800px"
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd([value]);

          if (success) {
            handleModalVisible(false);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        {generateForm(columns, {defaultVal: false})}
      </ModalForm>
      {/* <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate(value);

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);

          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      /> */}

      <DrawerForm
        width={500}
        visible={showDetail}
        onVisibleChange={setShowDetail}
        onFinish={async (data) => {
          console.log(data)
          const id = currentRow.id
          setCurrentRow(undefined);
          setShowDetail(false);
          if (handleUpdate(id ,data)) {
            actionRef.current?.reloadAndRest?.();
            return true
          }
          return false
        }}
        title={intl.formatMessage({
          id: 'pages.courseTable.Edit',
          defaultMessage: 'Edit course',
        })}
        drawerProps={{
          forceRender: true,
          destroyOnClose: true,
        }}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
      >
        {generateForm(columns, {defaultRow: () => currentRow, disabled: ['stu_id']})}
      </DrawerForm>
    </PageContainer>
  );
};

export default courseList;
